﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Common.Util.Text;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ST.Buz.Service
{
	/// <summary>
	/// 微信提醒服务
	/// </summary>
	public partial class HostedServiceWXRemind : IHostedService
	{
		private readonly ILogger logger;
		private readonly IServiceProvider services;
		private Timer timer;

		public HostedServiceWXRemind(IServiceProvider _services,
			ILogger<HostedServiceWXRemind> log)
		{
			services = _services;
			logger = log;

		}

		public Task StartAsync(CancellationToken cancellationToken)
		{
			logger.LogDebug("定时微信提醒开始");
			timer = new Timer(Execute, null, TimeSpan.Zero, TimeSpan.FromSeconds(20));
			return Task.CompletedTask;
		}

		public Task StopAsync(CancellationToken cancellationToken)
		{
			logger.LogDebug("定时微信提醒结束");
			timer?.Change(Timeout.Infinite, 0);
			return Task.CompletedTask;
		}

		public virtual void Dispose()
		{
			timer?.Dispose();
		}

		private void Execute(object state = null)
		{
			try
			{
				using (var scope = services.CreateScope())
				{
					var sp = scope.ServiceProvider;
					BuzContext context = sp.GetRequiredService<BuzContext>();

					try
					{
						var lstData = (from l in context.WXTplMsgLog
									   where l.RemindState == (int)WXMessageRemindState.未发送
									   select l).ToList();
						var paras = new JObject();
						foreach (var data in lstData)
						{
							if (string.IsNullOrEmpty(data.AppID) || string.IsNullOrEmpty(data.OpenID) || string.IsNullOrEmpty(data.TplCode))
							{
								continue;
							}
							paras["appid"] = data.AppID;
							paras["touser"] = data.OpenID;
							paras["tplid"] = data.TplCode;
							paras["url"] = data.Url;
							if (!string.IsNullOrEmpty(data.XCXID))
							{
								paras["xcxid"] = data.XCXID;
							}
							if (!string.IsNullOrEmpty(data.XCXPagePath))
							{
								paras["xcxpage"] = data.XCXPagePath;
							}
							paras["data"] = JsonConvert.DeserializeObject<JArray>(data.TplData);
							try
							{
								var resp = HttpHelper.Post("https://wx.sqcdrj.com/oauth/wx/mp/sendtplmsg", paras, 5);
								logger.LogInformation($"发送微信消息到{data.OpenID}，返回：{resp}");
								try
								{
									context.Database.ExecuteSqlInterpolated($"UPDATE WX_TplMsgLog SET RemindState={(int)WXMessageRemindState.发送成功}");
								}
								catch (Exception e)
								{
									logger.LogError(e, $"更新发送微信消息到{data.OpenID}状态出错：" + (e.InnerException != null ? e.InnerException.Message : e.Message));
								}
							}
							catch (Exception ex)
							{
								try
								{
									context.Database.ExecuteSqlInterpolated($"UPDATE WX_TplMsgLog SET RemindState={(int)WXMessageRemindState.发送失败}");
								}
								catch (Exception e)
								{
									logger.LogError(e, $"更新发送微信消息到{data.OpenID}状态出错：" + (e.InnerException != null ? e.InnerException.Message : e.Message));
								}
								logger.LogError(ex, $"发送微信消息到{data.OpenID}出错：" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
							}
						}
					}
					catch (Exception ex)
					{
						logger.LogError(ex.InnerException ?? ex, "发送微信消息出错");
					}
				}
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "发送微信消息出错");
			}
		}
	}
}